/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-07-20 09:42:59
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-26 14:26:22
 * @FilePath: \ems_neutral_app\lib\pages\Login\LoginGuidPage.dart
 * @Description: 登录+引导页
 */
import 'package:ems_neutral_app/base/SilScaffold.dart';
import 'package:ems_neutral_app/common/widgets/cubitWidget/BottomSheetView.dart';
import 'package:ems_neutral_app/pages/Login/ForgetPwdGuidPage.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/router/ARouter.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';

import '../../common/Method/CommonMethod.dart';
import '../../common/widgets/cubitWidget/SubmitBtn.dart';
import '../Mine/Language/LanguageController.dart';
import 'Controller/LoginController.dart';
import 'RegisterPage.dart';
import 'View/LoginProtocolWidget.dart';
import 'View/LoginRichTextView.dart';

class LoginGuidPage extends StatefulWidget {
  const LoginGuidPage({super.key});

  @override
  State<LoginGuidPage> createState() => _LoginGuidPageState();
}

class _LoginGuidPageState extends State<LoginGuidPage> {
  /// 当前语言
  LanguageController _languageController =
      Get.put<LanguageController>(LanguageController());

  /// 语言名称描述
  List<String> _languageDiscList = [];
  List<String> _languageList = [];
  String _curLang = '';

  String? _account;
  String? _passwrod;
  LoginController _loginController = Get.put(LoginController());

  GlobalKey<LoginProtocolWidgetState> _protocolWidgetKey = GlobalKey();
  bool _isPromptEnglish = true;

  @override
  void initState() {
    super.initState();
    _languageDiscList = _languageController.languageMap.values.toList();
    _languageList = _languageController.languageMap.keys.toList();
    _isPromptEnglish = _languageController.isPromptEnglish();
  }

  @override
  Widget build(BuildContext context) {
    _curLang = _languageController.getCurLanguageStr();

    return SilScaffold(
      sideMargin: 30.w,
      leftBackButtonHide: true,
      trailingWidget: navChooseLangBtn(),
      body: mainWidget(),
    );
  }

  navChooseLangBtn() {
    return SilButton(
      padding: EdgeInsets.only(right: 20.w),
      title: _curLang,
      titleColor: ColorUtils.color_font_main,
      fontSize: 14.sp,
      imagePosition: ImagePosition.Right,
      imgHeight: 9.w,
      imgWidth: 9.w,
      space: 5.w,
      imgPath: 'imgs/common/common_sanjx.png',
      onTapFunc: chooseLangSheetPop,
    );
  }

  chooseLangSheetPop() {
    SilBottomSheet.show(
        context: context,
        child: BottomSheetView(
          titles: _languageDiscList,
          initialSelectedItem: _languageDiscList.indexOf(_curLang),
          tapSureSeletedFunc: (selected) async {
            _curLang = _languageDiscList[selected];
            // 用户设置语言
            String language = _languageList[selected];
            await _languageController.settingLanguage(language);
            setState(() {});
          },
        ));
  }

  mainWidget() {
    Widget contentWidet = Container(
      margin: EdgeInsets.only(top: 25.w),
      child: Column(
        children: [
          // logo and slogan
          SilImage(
            _isPromptEnglish ? 'imgs/login/logoEN.png' : 'imgs/login/logo.png',
            width: 244.w,
            height: 90.w,
            margin: EdgeInsets.only(bottom: 50.w),
          ),

          loginInfoItem(
            onValid: (p0, p1) {
              _account = p1;
            },
          ),
          loginInfoItem(
            isPwd: true,
            onValid: (p0, p1) {
              _passwrod = p1;
            },
          ),
          forgetPwdBtn(), //忘记密码
          submitBtnWidget(), //登录按钮
          LoginRichTextView(
            leftTitle: LangOf(context)?.login?.noAccount,
            rightTitle: LangOf(context)?.login?.goRegister,
            onTap: () {
              /// 检查是否遵守用户协议
              if (!checkAgreeProtocol(agreeHandler: () {
                ARoute.gotoPage(context, RegisterPage());
              })) return;
              ARoute.gotoPage(context, RegisterPage());
            },
          ), //注册
        ],
      ),
    );

    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          contentWidet,

          /// 协议
          LoginProtocolWidget(
            key: _protocolWidgetKey,
          ),
        ],
      ),
    );
  }

  /// 检查是否同意协议
  checkAgreeProtocol({Function? agreeHandler}) {
    bool? isAllowed = _protocolWidgetKey.currentState?.isAllowed;
    if (isAllowed != true) {
      _protocolWidgetKey.currentState?.showDialog(agreeHandler: agreeHandler);
    }

    return isAllowed;
  }

  submitBtnWidget() {
    return Container(
      alignment: Alignment.center,
      child: SubmitBtn(
        margin: EdgeInsets.only(top: 10.w),
        title: LangOf(context)?.login?.login,
        onTapFunc: () {
          /// 检查是否遵守用户协议
          if (!checkAgreeProtocol(agreeHandler: () {
            // 隐藏键盘
            globalTextFieldDismiss(context);
            _loginController.login(
                context: context,
                phone: _account,
                password: _passwrod,
                loginMethod: LoginMethod.LoginMethodByPassword);
          })) return;
          // 隐藏键盘
          globalTextFieldDismiss(context);
          _loginController.login(
              context: context,
              phone: _account,
              password: _passwrod,
              loginMethod: LoginMethod.LoginMethodByPassword);
        },
      ),
    );
  }

  /// 忘记密码
  forgetPwdBtn() {
    return Container(
      margin: EdgeInsets.only(top: 20.w),
      alignment: Alignment.centerRight,
      child: SilButton(
        title: LangOf(context)?.login?.forgetpwd,
        titleColor: ColorUtils.color_theme,
        fontSize: 14.w,
        fontWeight: FontWeight.w400,
        padding: EdgeInsets.symmetric(vertical: 10.w),
        onTapFunc: () {
          /// 检查是否遵守用户协议
          if (!checkAgreeProtocol(agreeHandler: () {
            ARoute.gotoPage(context, ForgetPwdGuidPage());
          })) return;
          ARoute.gotoPage(context, ForgetPwdGuidPage());
        },
      ),
    );
  }

  /// 登录信息item
  loginInfoItem({bool isPwd = false, dynamic Function(bool, String)? onValid}) {
    String? hintTextPwd = LangOf(context)?.login?.passwordPlaceholder;
    String? hintTextAccount = LangOf(context)?.login?.accountPlaceholder;

    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.symmetric(vertical: 10.w),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
                  color: ColorUtils.color_divider_line, width: 0.5.w))),
      child: Row(
        children: [
          SilImage(
            isPwd ? 'imgs/login/login_pwd.png' : 'imgs/login/login_zh.png',
            height: 28.w,
            width: 28.w,
          ),
          Padding(padding: EdgeInsets.only(right: 20.w)),
          Expanded(
              child: SilTextField(
                  height: 50.w,
                  hintText: isPwd ? hintTextPwd : hintTextAccount,
                  onValid: (valid, value) {
                    if (onValid != null) onValid(valid, value);
                  },
                  isObscure: isPwd,
                  interface:
                      isPwd ? SilFormattersPwd() : SilFormattersNickName()))
        ],
      ),
    );
  }
}
